﻿using System;
using System.Collections.Generic;
using System.Linq;
using VSD.OneStopService.BLL;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Web.Security;
using Microsoft.Win32;
using System.Reflection;

public partial class Login : System.Web.UI.Page
{
    private string Regex_RemoveDuplicateSpaces = @"\s+";

    StaffRepository resStaff = new StaffRepository();
    string _assemblyLocation = "";
    const string AppKeyPath = "SOFTWARE\\VSD\\VSDOneStopService";

    string remoteUserName = string.Empty;
    string remotePassword = string.Empty;
    string logedUserName = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (!string.IsNullOrEmpty(remoteUserName) && !string.IsNullOrEmpty(remotePassword))
            {
                txtPassword.Text = remotePassword;
                txtUsername.Text = remoteUserName;
                DoLogin();
            }
            else
            {
                txtUsername.Focus();
                #region Read regedit

                //RegistryKey appReg = Registry.CurrentUser.CreateSubKey(AppKeyPath);
                //remoteUserName = (appReg.GetValue("UserName") != null) ? appReg.GetValue("UserName").ToString() : "";
                //remotePassword = (appReg.GetValue("Password") != null) ? appReg.GetValue("Password").ToString() : "";
                //string autoLogin = (appReg.GetValue("AutoLogin") != null) ? appReg.GetValue("AutoLogin").ToString() : "false";

                //chkRemember.Checked = (autoLogin.ToLower() == "false") ? false : true;
                //_assemblyLocation = Assembly.GetExecutingAssembly().Location;
                #endregion
            }

        }
    }

    private List<Staff> ChuyenVienPhong(int departmentID)
    {
        string roleChuyenVien = PermissionManager.ConvertCodeToRole(PermissionCode.CHUYENVIEN_XULY);
        string[] AllChuyenVien = Roles.GetUsersInRole(roleChuyenVien);// Danh sách có quyền chuyen vien
        List<Staff> TempChuyenViens = resStaff.GetStaffByUserNames(AllChuyenVien);
        List<Staff> DSChuyenVien = new List<Staff>();
        foreach (Staff s in TempChuyenViens)
        {
            if (s.DepartmentID == departmentID)
            {
                DSChuyenVien.Add(s);
            }
        }
        return DSChuyenVien;
    }

    private List<Staff> LanhDaoPhong(int departmentID)
    {
        string roleTruongPhong = PermissionManager.ConvertCodeToRole(PermissionCode.LANHDAO_PHONG_CHUYENMON);
        string[] TruongPhongs = Roles.GetUsersInRole(roleTruongPhong);// Danh sách có quyền trưởng phòng

        return resStaff.GetStaffByUserNames(TruongPhongs);
    }
    private List<Staff> LanhDaoCoQuan()
    {
        try
        {
            string roleLanhDao = PermissionManager.ConvertCodeToRole(PermissionCode.LANHDAO_COQUAN);
            string roleLanhDaoVPs = PermissionManager.ConvertCodeToRole(PermissionCode.LANHDAO_VP);

            string[] LanhDaos = Roles.GetUsersInRole(roleLanhDao);// Danh sách có quyền lãnh đạo cơ quan
            string[] LanhDaoVPs = Roles.GetUsersInRole(roleLanhDaoVPs);// Danh sách có quyền ký hồ sơ

            List<Staff> lanhDaoVP = resStaff.GetStaffByUserNames(LanhDaoVPs);
            ContextUser.DSLanhDaoVP = lanhDaoVP;

            List<Staff> lanhDaoVPKy = new List<Staff>();
            foreach (Staff item in lanhDaoVP)
            {
                PermissionManager p = new PermissionManager(item.UserName);
                if (p.HasPermission(PermissionCode.KY_HOSO))
                {
                    lanhDaoVPKy.Add(item);
                }
            }
            ContextUser.DSLanhDaoVPKy = lanhDaoVPKy;

            List<Staff> staffs = new List<Staff>();
            staffs.AddRange(resStaff.GetStaffByUserNames(LanhDaos));
            foreach (Staff s in lanhDaoVPKy)
            {
                if (!staffs.Contains(s))
                    staffs.Add(s);
            }
            return staffs;
        }
        catch { return null; }
    }

    private void DoLogin()
    {
        #region Check login
        if (string.IsNullOrEmpty(txtPassword.Text) || string.IsNullOrEmpty(txtUsername.Text.Trim()))
        {
            lbMessage.Text = "Nhập vào đầy đủ thông tin đăng nhập";
            txtUsername.Focus();
            return;
        }
        try
        {
            logedUserName = txtUsername.Text.Trim().ToLower();
            logedUserName = Regex.Replace(logedUserName, Regex_RemoveDuplicateSpaces, " ");
            HttpContext.Current.Session["AdminLogined"] = logedUserName;
            if (Membership.ValidateUser(logedUserName, txtPassword.Text))
            {
                StaffRepository staffRepository = new StaffRepository();
                lbMessage.Text = "Đăng nhập thành công.";
                ContextUser.IsLogged = true;
                ContextUser.UserName = logedUserName;

                //Context.CurrentUser = new StaffRepository().GetStaffByUserName(txtUserName.Text.Trim());

                Staff staff = staffRepository.GetStaffByUserName(logedUserName);
                if (staff == null)
                {
                    staff = new Staff();
                    staff.UserName = logedUserName;
                    staffRepository.Add(staff);
                    staffRepository.SubmitChanges();
                }

                ContextUser.CurrentUser = staff;
                ContextUser.PermissionCollection = new PermissionManager(staff.UserName);
                try
                {
                    ContextUser.CurrentDepartment = new DepartmentRepository().Get(staff.DepartmentID.Value);
                    ContextUser.DSChuyenVien = ChuyenVienPhong(staff.DepartmentID.Value);
                    ContextUser.DSLanhDaoPhong = LanhDaoPhong(staff.DepartmentID.Value);
                }
                catch { }
                ContextUser.DSLanhDaoCQ = LanhDaoCoQuan();

                CustomizationRepository resCustomize = new CustomizationRepository();
                ContextUser.GlobalOption = resCustomize.GetGlobalOption();
                ContextUser.IndividualOption = resCustomize.GetByUserName(logedUserName);
                string IDs = resCustomize.GetServiceIDsByUserName(logedUserName);
                if (!string.IsNullOrEmpty(IDs))
                {
                    string temp = IDs.Substring(1);
                    ContextUser.ServiceQuickSelect = temp.Split(',').ToList();
                }
                else
                {
                    ContextUser.ServiceQuickSelect = new List<string>();
                }

                if (logedUserName == "administrator")
                {
                    ContextUser.IsSystemAccount = true;
                }

                //Session["ContextUser"] = ContextUser;

                FormsAuthentication.SetAuthCookie(logedUserName, chkRemember.Checked);
                Response.Redirect("~/default.aspx");
            }
            else
            {
                lbMessage.Text = "Đăng nhập không thành công.";
                ContextUser.IsLogged = false;
            }

        }
        catch (Exception)
        {
            lbMessage.Text = "Lỗi trong quá trình đăng nhập";
        }

        #endregion
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        #region Write regedit

        RegistryKey appReg = Registry.CurrentUser.CreateSubKey(AppKeyPath);
        if (chkRemember.Checked)
        {
            string saveUserName = Regex.Replace(txtUsername.Text.Trim(), Regex_RemoveDuplicateSpaces, " ");
            appReg.SetValue("Password", txtPassword.Text);
            appReg.SetValue("UserName", saveUserName);
        }
        else
        {
            appReg.SetValue("Password", "");
            appReg.SetValue("UserName", "");
        }
        appReg.SetValue("AutoLogin", chkRemember.Checked.ToString());
        #endregion
        DoLogin();

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        txtPassword.Text = null;
        txtUsername.Text = null;
        chkRemember.Checked = false;
        txtUsername.Focus();
    }
}